package com.ycc.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.ycc.springcloud.pojo.Dept;
import com.ycc.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

///提供Restful服务
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient client;


    /**
     * 服务熔断：针对于服务器使用，某个服务器异常，引起熔断。
     * 相当于保险丝，防止这个服务异常的服务前的服务雪崩
     */
    @HystrixCommand(fallbackMethod = "hystrixGets")
    @RequestMapping("/dept/gets/{id}")
    public Dept gets(@PathVariable("id")Long id){
        Dept dept = deptService.queryById(id);
        if (dept==null){
            throw new RuntimeException("id=>"+id+",不存在该用户！");
        }
        return dept;
    }
    public Dept hystrixGets(@PathVariable("id")Long id){
        Dept dept = new Dept()
                .setDeptno(id)
                .setDeptname("id=>"+id+",不存在该用户！")
                .setDb_source("no this database in mysql");
        return dept;
    }





    @RequestMapping("/dept/add")
    public int addDept(Dept dept){
        return deptService.addDept(dept);
    }

    @RequestMapping("/dept/get/{id}")
    public Dept addDept(@PathVariable("id") Long id){
        Dept dept = deptService.queryById(id);
        if (dept==null){
            throw new RuntimeException("Fail");
        }
        return dept;
    }

    @RequestMapping("/dept/list")
    public List<Dept> addDept(){
        return deptService.queryAll();
    }

    @RequestMapping("/dept/discovery")
    public Object discovery(){
        //获取微服务列表清单
        List<String> services = client.getServices();

        //得到一个具体的微服务信息，通过具体的微服务id
        List<ServiceInstance> instances = client.getInstances("SPRING-CLOUD-PROVIDER-DEPT");

        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost()+"\t"+
                    instance.getPort()+"\t"+
                    instance.getUri()+"\t"+
                    instance.getServiceId()
            );
        }
        return this.client;
    }









}
